﻿# -*- coding: utf-8 -*-

from glob import glob
import re
import os.path
import os
import sys
import sqlite3
import time

if len(sys.argv) < 3:
    print """
    Uso: wiki_replace.py old_expression new_expression
    
    Replace an expression in all wiki matches in all projects in current folder.
    
    """
    sys.exit(-1)

projects = glob(os.path.join(os.getcwd(), "*"))

expr_replace = re.compile(sys.argv[1], re.DOTALL)

for project in projects:
    db_file = os.path.join(project,"db", "trac.db")
    if os.path.exists(db_file):
        print "Replacing in %s" % project
        print "-----------------------------------------------"
    
    db = sqlite3.connect(db_file)
    
    cur = db.cursor()
    cur.execute("""
    select * from wiki w
    where text like ? 
        and version = (select max(version) from wiki where name = w.name)
        order by name asc""", ('%' + sys.argv[1] + '%',))
    
    rows = cur.fetchall()
    
    #Find column numbers
    for i in range(len(cur.description)):
        if cur.description[i][0] == 'name':
            col_name = i
        elif cur.description[i][0] == 'version':
            col_version = i
        elif cur.description[i][0] == 'author':
            col_author = i
        elif cur.description[i][0] == 'readonly':
            col_readonly = i
        elif cur.description[i][0] == 'text':
            col_text = i
    
    for row in rows:
        text = row[col_text]
        match = expr_replace.search(text)
        if match:
            print "%s: v%s" % (row[col_name], row[col_version])
            sample_str = row[col_text][match.start()-20:match.end()+20].replace("\n", "").replace("\r", "")
            print "  <<< ...%s..." % sample_str
            print "  >>> ...%s..." % expr_replace.sub(sys.argv[2], sample_str)
            print "  Apply changes? (Y/n)",
            ans = raw_input()
            if ans in ('', 's', 'S', 'y', 'Y'):
                newtext = expr_replace.sub(sys.argv[2], text)
                db.execute("""
                    insert into wiki (name, version, time, author, ipnr, text, comment, readonly)
                    values (?,?,?,?,?,?,?,?)""",
                    (row[col_name],int(row[col_version]) + 1, int(time.time()),
                    row[col_author], '127.0.0.1', newtext, '', row[col_readonly]))
    
    db.commit()
    db.close()
